package com.company.project.controller.ldjsc.weather;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.company.project.entity.ldjsc.calendar.ZyCalendarEntity;
import com.company.project.entity.ldjsc.weather.ZyCityCodeEntity;
import com.company.project.entity.ldjsc.weather.ZyCityCodeJuheEntity;
import com.company.project.entity.ldjsc.weather.ZyWeatherRealtimeEntity;
import com.company.project.entity.ldjsc.weather.ZyWeatherSevenEntity;
import com.company.project.service.ldjsc.calendar.ZyCalendarService;
import com.company.project.service.ldjsc.weather.ZyCityCodeJuheService;
import com.company.project.service.ldjsc.weather.ZyCityCodeService;
import com.company.project.service.ldjsc.weather.ZyWeatherRealtimeService;
import com.company.project.service.ldjsc.weather.ZyWeatherSevenService;
import com.company.project.vo.initial.resp.WeatherVo;
import com.company.project.vo.initial.resp.ZyWeatherRealtimeVo;
import com.company.project.vo.initial.resp.ZyWeatherSevenVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import com.company.project.common.utils.DataResult;


/**
 * 天气(未来5天)
 *
 * @author wenbin
 * @email *****@mail.com
 * @date 2025-07-21 17:56:53
 */
@Controller
@RequestMapping("/sxzy/weathers")
public class ZyWeatherSevenController {
    @Autowired
    private ZyWeatherSevenService zyWeatherSevenService;

    @Autowired
    private ZyWeatherRealtimeService zyWeatherRealtimeService;

    @Autowired
    private ZyCityCodeService zyCityCodeService;

    @Autowired
    private ZyCityCodeJuheService zyCityCodeJuheService;

    @Autowired
    private ZyCalendarService zyCalendarService;

    @Value("${tq.api-juhe1.key}")
    private String keyJuhe1;
    @Value("${tq.api-juhe1.url}")
    private String urlJuhe1;
    @Value("${tq.api-juhe2.key}")
    private String keyJuhe2;
    @Value("${tq.api-juhe2.url}")
    private String urlJuhe2;
    @Value("${tq.api-juhe3.key}")
    private String keyJuhe3;
    @Value("${tq.api-juhe3.url}")
    private String urlJuhe3;

    /**
     * 未来5天天气（市县都调用聚合数据接口一天运行一次 测试环境不运行）
     *
     * @return
     */
    @GetMapping("/city/five")
    @ResponseBody
    public DataResult citySeven(String city) {

//        getWeatherSeven();

        LambdaQueryWrapper<ZyWeatherSevenEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(ZyWeatherSevenEntity::getCityName, city);
        queryWrapper.orderByDesc(ZyWeatherSevenEntity::getCreateDate);
        queryWrapper.last("limit 5");
        List<ZyWeatherSevenEntity> list = zyWeatherSevenService.list(queryWrapper);
        return DataResult.success(list);

    }

    /**
     * 获取市级实时天气和未来5天天气
     */
    @GetMapping("/municipality")
    @ResponseBody
    public DataResult municipality(String municipality) {

        List<String> citys = new ArrayList<>();


        if (StringUtils.isNotBlank(municipality)) {
            //获取一级城市的id
            LambdaQueryWrapper<ZyCityCodeEntity> queryWrapperCityCode = Wrappers.lambdaQuery();
            String substring = municipality.substring(0, 2);
            queryWrapperCityCode.eq(ZyCityCodeEntity::getCityName, substring);
            queryWrapperCityCode.last("limit 1");
            ZyCityCodeEntity zyCityCodeEntity = zyCityCodeService.getOne(queryWrapperCityCode);

            //获取二级城市列表
            Long id = zyCityCodeEntity.getId();
            LambdaQueryWrapper<ZyCityCodeEntity> lqwCityCode = Wrappers.lambdaQuery();
            lqwCityCode.eq(ZyCityCodeEntity::getSuperiorId, id);
            List<ZyCityCodeEntity> list = zyCityCodeService.list(lqwCityCode);
            for (ZyCityCodeEntity zyCityCodeEntity1 : list) {
                citys.add(zyCityCodeEntity1.getCityName());
            }
        } else {
            List<ZyCityCodeJuheEntity> list = zyCityCodeJuheService.list();
            for (ZyCityCodeJuheEntity zyCityCodeJuheEntity : list) {
                citys.add(zyCityCodeJuheEntity.getCityName());
            }
        }

        List<WeatherVo> weatherVos = new ArrayList<>();

        LocalDate today = LocalDate.now();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = today.format(dateFormatter);

        for (String city : citys) {

            WeatherVo weatherVo = new WeatherVo();
            weatherVo.setCityName(city);
            ZyWeatherRealtimeVo zyWeatherRealtimeVo = new ZyWeatherRealtimeVo();

            if (StringUtils.isNotBlank(municipality)) {

//            city = city + "市";
                //实时天气
                LambdaQueryWrapper<ZyWeatherRealtimeEntity> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.like(ZyWeatherRealtimeEntity::getCityName, municipality);
                queryWrapper.orderByDesc(ZyWeatherRealtimeEntity::getCreateDate);
                queryWrapper.last("limit 1");
                ZyWeatherRealtimeEntity zyWeatherSeven = zyWeatherRealtimeService.getOne(queryWrapper);

                if (zyWeatherSeven != null) {
                    BeanUtils.copyProperties(zyWeatherSeven, zyWeatherRealtimeVo);
                }
            } else {
                //实时天气
                LambdaQueryWrapper<ZyWeatherRealtimeEntity> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.like(ZyWeatherRealtimeEntity::getCityName, city);
                queryWrapper.orderByDesc(ZyWeatherRealtimeEntity::getCreateDate);
                queryWrapper.last("limit 1");
                ZyWeatherRealtimeEntity zyWeatherSeven = zyWeatherRealtimeService.getOne(queryWrapper);

                if (zyWeatherSeven != null) {
                    BeanUtils.copyProperties(zyWeatherSeven, zyWeatherRealtimeVo);
                }
            }

            //未来5天
            LambdaQueryWrapper<ZyWeatherSevenEntity> queryWrapper1 = Wrappers.lambdaQuery();
            //根据城市查询
            queryWrapper1.like(ZyWeatherSevenEntity::getCityName, city);
            //获取日期大于等于今天
            queryWrapper1.ge(ZyWeatherSevenEntity::getDate, format);
            //当前时间大于今天0点10分（查询今天生成的数据）
            if (LocalDateTime.now().isAfter(LocalDate.now().atTime(0, 30))) {
                queryWrapper1.gt(ZyWeatherSevenEntity::getCreateDate, format);
            } else {
                //查询昨天生成的数据
                queryWrapper1.lt(ZyWeatherSevenEntity::getCreateDate, LocalDate.now().minusDays(1).toString());
            }
            queryWrapper1.orderByDesc(ZyWeatherSevenEntity::getCreateDate);
            queryWrapper1.last("limit 5");

            List<ZyWeatherSevenEntity> zyWeatherSevenEntities = new ArrayList<>();
            zyWeatherSevenEntities = zyWeatherSevenService.list(queryWrapper1);

            if (zyWeatherSevenEntities == null || zyWeatherSevenEntities.size() < 5) {
                //如果没有数据则调用自动生成
                getWeatherSeven(city);
            }
            zyWeatherSevenEntities = zyWeatherSevenService.list(queryWrapper1);
            //5天正排序
            List<Long> ids = new ArrayList<>();
            for (ZyWeatherSevenEntity zyWeatherSevenEntity : zyWeatherSevenEntities) {
                ids.add(zyWeatherSevenEntity.getId());
            }
            List<ZyWeatherSevenEntity> list = new ArrayList<>();
            if (ids.size() > 0) {
                LambdaQueryWrapper<ZyWeatherSevenEntity> queryWrapper2 = Wrappers.lambdaQuery();
                queryWrapper2.in(ZyWeatherSevenEntity::getId, ids);
                queryWrapper2.orderByAsc(ZyWeatherSevenEntity::getDate);
                list = zyWeatherSevenService.list(queryWrapper2);
            }

            List<ZyWeatherSevenVo> zyWeatherSevenVos = new ArrayList<>();

            for (ZyWeatherSevenEntity zyWeatherSevenEntity : list) {
                ZyWeatherSevenVo zyWeatherSevenVo = new ZyWeatherSevenVo();
                //获取当前日期是周几
                String date = zyWeatherSevenEntity.getDate();

                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate startDate = LocalDate.parse(date, formatter);
                DayOfWeek dayOfWeek = startDate.getDayOfWeek();
                String weekDay = "";
                if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
                    weekDay = "周六";
                } else if (dayOfWeek.equals(DayOfWeek.SUNDAY)) {
                    weekDay = "周日";
                } else if (dayOfWeek.equals(DayOfWeek.MONDAY)) {
                    weekDay = "周一";
                } else if (dayOfWeek.equals(DayOfWeek.TUESDAY)) {
                    weekDay = "周二";
                } else if (dayOfWeek.equals(DayOfWeek.WEDNESDAY)) {
                    weekDay = "周三";
                } else if (dayOfWeek.equals(DayOfWeek.THURSDAY)) {
                    weekDay = "周四";
                } else if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
                    weekDay = "周五";
                }

                BeanUtils.copyProperties(zyWeatherSevenEntity, zyWeatherSevenVo);
                zyWeatherSevenVo.setWeekDay(weekDay);

                //获取月
                String month = date.substring(5, 7);
                if (month.startsWith("0")) {
                    month = month.substring(1);
                }
                //获取日
                String day = date.substring(8, 10);
                if (day.startsWith("0")) {
                    day = day.substring(1);
                }
                zyWeatherSevenVo.setLivelihood(month + "月" + day + "日");

                //温度
                String temperature = zyWeatherSevenEntity.getTemperature();
                String[] parts = temperature.split("/");

                //最低
                String min = parts[0] + "℃";
                //最高
                String max = parts[1];
                zyWeatherSevenVo.setMaxTemperature(max);
                zyWeatherSevenVo.setMinTemperature(min);
//                zyWeatherSevenVo.setTemperature(min + "/" + max);


                //天气图标
                String weather = zyWeatherSevenVo.getWeather();
                if (weather.contains("转")) {
                    weather = weather.substring(0, weather.indexOf("转"));
                }

                if (weather.equals("晴")) {
                    zyWeatherSevenVo.setIconDict("1");
                } else if (weather.equals("多云")) {
                    zyWeatherSevenVo.setIconDict("2");
                } else if (weather.equals("阴")) {
                    zyWeatherSevenVo.setIconDict("3");
                } else if (weather.equals("雾")) {
                    zyWeatherSevenVo.setIconDict("4");
                } else if (weather.equals("大雨")) {
                    zyWeatherSevenVo.setIconDict("5");
                } else if (weather.equals("中雨")) {
                    zyWeatherSevenVo.setIconDict("6");
                } else if (weather.equals("阵雨")) {
                    zyWeatherSevenVo.setIconDict("7");
                } else if (weather.equals("暴雪")) {
                    zyWeatherSevenVo.setIconDict("8");
                } else if (weather.equals("暴雨")) {
                    zyWeatherSevenVo.setIconDict("9");
                } else if (weather.equals("冰雹")) {
                    zyWeatherSevenVo.setIconDict("10");
                } else if (weather.equals("大雪")) {
                    zyWeatherSevenVo.setIconDict("11");
                } else if (weather.equals("雷阵雨")) {
                    zyWeatherSevenVo.setIconDict("12");
                } else if (weather.equals("小雪")) {
                    zyWeatherSevenVo.setIconDict("13");
                } else if (weather.equals("小雨")) {
                    zyWeatherSevenVo.setIconDict("14");
                } else if (weather.equals("阵雪")) {
                    zyWeatherSevenVo.setIconDict("15");
                } else if (weather.equals("中雪")) {
                    zyWeatherSevenVo.setIconDict("16");
                } else {
                    zyWeatherSevenVo.setIconDict("1");
                }
                zyWeatherSevenVos.add(zyWeatherSevenVo);
            }
            if (zyWeatherSevenVos.size() > 0) {
                zyWeatherRealtimeVo.setZyWeatherSevenVo(zyWeatherSevenVos.get(0));
            }
            weatherVo.setZyWeatherRealtimeVo(zyWeatherRealtimeVo);
            weatherVo.setZyWeatherSevenVos(zyWeatherSevenVos);
            weatherVos.add(weatherVo);
        }
        return DataResult.success(weatherVos);
    }


    //自动生成未来5天天气数据（0点20自动生成）（首次生成）
    @Scheduled(cron = "0 20 0 * * ?")
    private void automaticTwenty() {
        List<ZyCityCodeEntity> list = zyCityCodeService.list();
        for (ZyCityCodeEntity zyCityCodeEntity : list) {
            getWeatherSeven(zyCityCodeEntity.getCityName());
            System.out.println(LocalDateTime.now() + "成功生成" + zyCityCodeEntity.getCityName() + "的5天天气数据");
        }
    }

    //自动生成未来5天天气数据（0点40自动生成）（防止第一次未生成）
    @Scheduled(cron = "0 40 0 * * ?")
    private void automaticForty() {
        List<ZyCityCodeEntity> list = zyCityCodeService.list();
        for (ZyCityCodeEntity zyCityCodeEntity : list) {

            LambdaQueryWrapper<ZyWeatherSevenEntity> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.like(ZyWeatherSevenEntity::getCityName, zyCityCodeEntity.getCityName());
            //查询创建日期是当天生成的数据
            queryWrapper.like(ZyWeatherSevenEntity::getCreateDate, LocalDate.now());
            List<ZyWeatherSevenEntity> zyWeatherSevenEntities = zyWeatherSevenService.list(queryWrapper);
            if (zyWeatherSevenEntities.size() == 0 || zyWeatherSevenEntities.size() < 5){
                getWeatherSeven(zyCityCodeEntity.getCityName());
                System.out.println(LocalDateTime.now() + "成功生成" + zyCityCodeEntity.getCityName() + "的5天天气数据");
            }
        }
    }

    /**
     * 获取天气数据(未来5天)
     * 每晚12点10分自动运行一次
     */
//    @Scheduled(cron = "0 10 0 * * ?")
    private void getWeatherSeven(String city) {

        //根据城市名称获取城市信息
        LambdaQueryWrapper<ZyCityCodeEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(ZyCityCodeEntity::getCityName, city);
        ZyCityCodeEntity zyCityCodeEntity = zyCityCodeService.getOne(queryWrapper);

        String requestUrl;
        if (zyCityCodeEntity.getNode().equals("1")) {
            requestUrl = urlJuhe1 + "?key=" + keyJuhe1 + "&city=" + zyCityCodeEntity.getCityName();
        } else if (zyCityCodeEntity.getNode().equals("2")) {
            requestUrl = urlJuhe2 + "?key=" + keyJuhe2 + "&city=" + zyCityCodeEntity.getCityName();
        } else {
            requestUrl = urlJuhe3 + "?key=" + keyJuhe3 + "&city=" + zyCityCodeEntity.getCityName();
        }
        try {
            URL obj = new URL(requestUrl);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");

            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String line;
            StringBuilder response = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 解析 JSON 数据
            JSONObject result = JSONObject.parseObject(response.toString());

            if (result.getIntValue("error_code") != 0) {
                throw new RuntimeException("API 调用失败：" + result.getString("reason"));
            }

            JSONObject resultData = result.getJSONObject("result");
            JSONArray futureArray = resultData.getJSONArray("future");

            if (futureArray == null || futureArray.isEmpty()) {
                throw new RuntimeException("未获取到未来天气数据");
            }

            // 构建返回数据
            for (int j = 0; j < futureArray.size(); j++) {
                JSONObject day = futureArray.getJSONObject(j);
                ZyWeatherSevenEntity zyWeatherSevenEntity = new ZyWeatherSevenEntity();
                zyWeatherSevenEntity.setWeather(day.getString("weather"));
                zyWeatherSevenEntity.setTemperature(day.getString("temperature"));
                zyWeatherSevenEntity.setCityName(zyCityCodeEntity.getCityName());
                zyWeatherSevenEntity.setDate(day.getString("date"));
                zyWeatherSevenService.save(zyWeatherSevenEntity);
                System.out.println("保存成功：" + zyCityCodeEntity.getCityName() + "，时间：" + LocalDateTime.now() + "（未来5天）");
                Thread.sleep(1000);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取天气数据失败：" + e.getMessage());
        }
    }

    /**
     * 跳转到页面
     */
    @GetMapping("/index/zyWeatherSeven")
    public String zyWeatherSeven() {
        return "zyweatherseven/list";
    }


    @ApiOperation(value = "查询分页数据")
    @PostMapping("zyWeatherSeven/listByPage")
    @SaCheckPermission("zyWeatherSeven:list")
    @ResponseBody
    public DataResult findListByPage(@RequestBody ZyWeatherSevenEntity zyWeatherSeven) {
        LambdaQueryWrapper<ZyWeatherSevenEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        queryWrapper.eq(zyWeatherSeven.getId() != null, ZyWeatherSevenEntity::getId, zyWeatherSeven.getId());
        queryWrapper.orderByDesc(ZyWeatherSevenEntity::getId);
        IPage<ZyWeatherSevenEntity> iPage = zyWeatherSevenService.page(zyWeatherSeven.getQueryPage(), queryWrapper);
        return DataResult.success(iPage);
    }


    @ApiOperation(value = "新增")
    @PostMapping("zyWeatherSeven/add")
    @SaCheckPermission("zyWeatherSeven:add")
    @ResponseBody
    public DataResult add(@RequestBody ZyWeatherSevenEntity zyWeatherSeven) {
        zyWeatherSevenService.save(zyWeatherSeven);
        return DataResult.success();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("zyWeatherSeven/delete")
    @SaCheckPermission("zyWeatherSeven:delete")
    @ResponseBody
    public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids) {
        zyWeatherSevenService.removeByIds(ids);
        return DataResult.success();
    }

    @ApiOperation(value = "更新")
    @PutMapping("zyWeatherSeven/update")
    @SaCheckPermission("zyWeatherSeven:update")
    @ResponseBody
    public DataResult update(@RequestBody ZyWeatherSevenEntity zyWeatherSeven) {
        zyWeatherSevenService.updateById(zyWeatherSeven);
        return DataResult.success();
    }


}
